﻿
async function get(url, data, options) {
    
    let queryString = '';
    if (data && Object.keys(data).length > 0) {
        queryString = Object.keys(data)
            .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
            .join('&');
    }
    // 只有当queryString非空时才拼接到URL上
    url = queryString ? `${url}?${queryString}` : url;
   
    return request(url, { ...options, method: 'GET' });
} 
async function post(url, data, options) {
    return request(url, { ...options, method: 'POST', body: JSON.stringify(data) });
} 
async function request(url, options) {
    const token = localStorage.getItem("token")??"";
    const response = await fetch(url, {
        ...options,
        headers: {
            'Content-Type': 'application/json',
            'Token': token
        },
    });
    if (!response.ok) {
        const error = new Error(response.statusText);
        error.response = response;
        throw error;
    }
    return response.json();
}
function timestampToDate(timestamp) {
    if(timestamp && timestamp.length<4){
        return timestamp;
    }
    var date = new Date(timestamp);
    var year = date.getFullYear();
    var month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的
    var day = ('0' + date.getDate()).slice(-2);
    var hours = ('0' + date.getHours()).slice(-2);
    var minutes = ('0' + date.getMinutes()).slice(-2);
    var seconds = ('0' + date.getSeconds()).slice(-2);
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
module.exports = {
    get, post,timestampToDate
}
